#define _GNU_SOURCE
#include <unistd.h>
#include "app_bluetooth.h"
#include <string.h>
#include <stdio.h>
#include "log/log.h"
#include "app_message.h"

/**
 * 等待获取蓝牙接收到ack数据（OK\r\n）
 */
static int wait_ack(Device *device){
    usleep(1000 * 50);
    char buf[4];
    read(device->fd,buf,4);
    if(memcmp(buf,"OK\r\n",4) == 0){
        return 0;
    }
    return -1;
}

//蓝牙是否可用  //获取蓝牙状态
int app_bluetooth_status(Device *device){
    write(device->fd,"AT\r\n",4);

    return wait_ack(device);
}

//蓝牙重命名
int app_bluetooth_rename(Device *device,char *name){
    write(device->fd,"AT+NAME=",7);
    write(device->fd,name,strlen(name));
    write(device->fd,"\r\n",2);

    return wait_ack(device);
}
//蓝牙设置波特率
int app_bluetooth_setBraudRate(Device *device,BTBraudRate baud_rate){
    write(device->fd,"AT+BAUD=",7);
    write(device->fd,baud_rate,1);
    write(device->fd,"\r\n",2);

    return wait_ack(device);
}
//蓝牙重置
int app_bluetooth_reset(Device *device){
    write(device->fd,"AT+RESET\r\n",10);

    return wait_ack(device);
}
//蓝牙设置网络ID
int app_bluetooth_setNetID(Device *device,char *net_id){
    write(device->fd,"AT+NETID=",8);
    write(device->fd,net_id,strlen(net_id));
    write(device->fd,"\r\n",2);

    return wait_ack(device);
}

//设置蓝牙MAC地址
int app_bluetooth_setMaddr(Device *device,char *maddr){
    write(device->fd,"AT+MADDR=",8);
    write(device->fd,maddr,strlen(maddr));
    write(device->fd,"\r\n",2);

    return wait_ack(device);
}

//处理读取的蓝牙数据的函数
int app_bluetooth_postRead(Device *device,char *data,int len);

//处理将要写入蓝牙数据的函数
int app_bluetooth_preWrite(Device *device,char *data,int len);